/*
 * results.java
 *
 * Created on 23-Sep-2009, 13:34:17
 * Copyright me
 */
package iffmyexp;

import com.icesoft.faces.component.ext.HtmlInputText;
import com.icesoft.faces.component.ext.HtmlPanelGrid;
import com.icesoft.faces.component.paneltabset.PanelTab;
import com.icesoft.faces.component.paneltabset.PanelTabSet;
import com.icesoft.faces.component.ext.HtmlDataTable;
import com.icesoft.faces.component.ext.HtmlOutputText;
import com.icesoft.faces.component.ext.UIColumn;
import com.sun.rave.web.ui.appbase.AbstractPageBean;
import java.util.Vector;
import javax.faces.FacesException;
import javax.faces.context.FacesContext;
import javax.faces.el.ValueBinding;
import javax.xml.xpath.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import tavernacon.*;

/**
 * <p>Page bean that corresponds to a similarly named JSP page.  This
 * class contains component definitions (and initialization code) for
 * all components that you have defined on this page, as well as
 * lifecycle methods and event handlers where you may add behavior
 * to respond to incoming events.</p>
 */
public class WorkflowResultsPage extends AbstractPageBean {

    String[] results;
    //Vector jobsVector;
    //Vector outputsVector;
    private DataValue dataValue = null;
    private JobDetails job = null;
    public DataValue[] outputs;
    static JobDetails[] jobDetails;
    static String selectedJobID;
    JobDetails selectedJob;
    SessionBean sessionBean = new SessionBean();
    FacesContext facesContext = FacesContext.getCurrentInstance();
    /*public String[] getOutputs(){
    return showOutputs();
    }

    public void setOutputs(String[] s){
    this.outputs = s;
    }*/
    public static int numberOfJobs = 4;
    public static PanelTabSet panelTabSet = new PanelTabSet();
    // <editor-fold defaultstate="collapsed" desc="Managed Component Definition">
    private int __placeholder;

    /**
     * <p>Automatically managed component initialization.  <strong>WARNING:</strong>
     * This method is automatically generated, so any user-specified code inserted
     * here is subject to being replaced.</p>
     */
    private void _init() throws Exception {
    }
    public static HtmlDataTable resultsTable = new HtmlDataTable();

    public HtmlDataTable getresultsTable() {
        return resultsTable;
    }

    public void setresultsTable(HtmlDataTable hdt) {
        this.resultsTable = hdt;
    }
    public static HtmlDataTable outputPortsTable = new HtmlDataTable();

    public HtmlDataTable getOutputPortsTable() {
        return outputPortsTable;
    }

    public void setOutputPortsTable(HtmlDataTable hdt) {
        this.outputPortsTable = hdt;
    }
    public static HtmlDataTable outputsTable = new HtmlDataTable();

    public HtmlDataTable getOutputsTable() {
        return outputsTable;
    }

    public void setOutputsTable(HtmlDataTable hdt) {
        this.outputsTable = hdt;
    }
    private PanelTabSet resultsTabSet = new PanelTabSet();

    public PanelTabSet getResultsTabSet() {
        return resultsTabSet;
    }

    public void setResultsTabSet(PanelTabSet pts) {
        this.resultsTabSet = pts;
    }

    /*public PanelTabSet getpanelTabSet() {
    this.panelTabSet = new PanelTabSet();
    List<UIComponent> children = this.panelTabSet.getChildren();

    for (int i = 0; i < numberOfJobs; i++) {
    PanelTab panelTab = new PanelTab();
    HtmlPanelGrid htmlPanelGrid = new HtmlPanelGrid();
    HtmlInputText htmlInputText = new HtmlInputText();

    htmlPanelGrid.getChildren().add(htmlInputText);
    panelTab.getChildren().add(htmlPanelGrid);

    children.add(panelTab);
    }
    return panelTabSet;
    }

    public void setpanelTabSet(PanelTabSet hdt) {
    this.panelTabSet = new PanelTabSet();
    List<UIComponent> children = this.panelTabSet.getChildren();

    for (int i = 0; i < numberOfJobs; i++) {
    PanelTab panelTab = new PanelTab();
    HtmlPanelGrid htmlPanelGrid = new HtmlPanelGrid();
    HtmlInputText htmlInputText = new HtmlInputText();

    htmlPanelGrid.getChildren().add(htmlInputText);
    panelTab.getChildren().add(htmlPanelGrid);

    children.add(panelTab);
    }
    }*/
    public static HtmlOutputText outs = new HtmlOutputText();

    public HtmlOutputText getouts() {
        return outs;
    }

    public void setouts(HtmlOutputText hot) {
        this.outs = hot;
    }
    public static HtmlOutputText outHeader = new HtmlOutputText();

    public HtmlOutputText getoutHeader() {
        return outHeader;
    }

    public void setoutHeader(HtmlOutputText hot) {
        this.outHeader = hot;
    }
    private static boolean jobsVis = false;

    public boolean getjobsVis() {
        return jobsVis;
    }

    public void setjobsVis(boolean jv) {
        this.jobsVis = jv;
    }
    private static boolean outsVis = false;

    public boolean getoutsVis() {
        return outsVis;
    }

    public void setoutsVis(boolean ov) {
        this.outsVis = ov;
    }
    private static boolean popupVis = false;

    public boolean getpopupVis() {
        return popupVis;
    }

    public void setpopupVis(boolean pv) {
        this.popupVis = pv;
    }
    public static boolean containsErrors = false;

    public boolean getcontainsErrors() {
        return containsErrors;
    }

    public void setcontainsErrors(boolean bo) {
        this.containsErrors = bo;
    }

    //icon displayed in the header to flag if there has been any errrors
    public static String errorsIcon = "";

    public String getErrorsIcon() {
        return errorsIcon;
    }

    public void setErrorsIcon(String bo) {
        this.errorsIcon = bo;
    }

    //String displayed as a tooltip in header of table to flag if there has been any errors
    public static String errorsMessage = "Contains no errors";

    public String getErrorsMessage() {
        return errorsMessage;
    }

    public void setErrorsMessage(String bo) {
        this.errorsMessage = bo;
    }

    // </editor-fold>
    /**
     * <p>Construct a new Page bean instance.</p>
     */
    public WorkflowResultsPage() {
    }

    /**
     * <p>Callback method that is called whenever a page is navigated to,
     * either directly via a URL, or indirectly via page navigation.
     * Customize this method to acquire resources that will be needed
     * for event handlers and lifecycle methods, whether or not this
     * page is performing post back processing.</p>
     * 
     * <p>Note that, if the current request is a postback, the property
     * values of the components do <strong>not</strong> represent any
     * values submitted with this request.  Instead, they represent the
     * property values that were saved for this view when it was rendered.</p>
     */
    @Override
    public void init() {
        // Perform initializations inherited from our superclass
        super.init();
        // Perform application initialization that must complete
        // *before* managed components are initialized
        // TODO - add your own initialiation code here

        // <editor-fold defaultstate="collapsed" desc="Managed Component Initialization">
        // Initialize automatically managed components
        // *Note* - this logic should NOT be modified
        try {
            _init();
        } catch (Exception e) {
            log("results Initialization Failure", e);
            throw e instanceof FacesException ? (FacesException) e : new FacesException(e);
        }

    // </editor-fold>
    // Perform application initialization that must complete
    // *after* managed components are initialized
    // TODO - add your own initialization code here
    }

    /**
     * <p>Callback method that is called after the component tree has been
     * restored, but before any event processing takes place.  This method
     * will <strong>only</strong> be called on a postback request that
     * is processing a form submit.  Customize this method to allocate
     * resources that will be required in your event handlers.</p>
     */
    @Override
    public void preprocess() {
    }

    /**
     * <p>Callback method that is called just before rendering takes place.
     * This method will <strong>only</strong> be called for the page that
     * will actually be rendered (and not, for example, on a page that
     * handled a postback and then navigated to a different page).  Customize
     * this method to allocate resources that will be required for rendering
     * this page.</p>
     */
    @Override
    public void prerender() {
    }

    /**
     * <p>Callback method that is called after rendering is completed for
     * this request, if <code>init()</code> was called (regardless of whether
     * or not this was the page that was actually rendered).  Customize this
     * method to release resources acquired in the <code>init()</code>,
     * <code>preprocess()</code>, or <code>prerender()</code> methods (or
     * acquired during execution of an event handler).</p>
     */
    @Override
    public void destroy() {
    }

    public String rowSelectionListener() {

        showOutputs();

        return null;

    }

    public String showJobs() {

        //jobsVector = new Vector();
        jobsVis = true;


        /*try {

        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser saxParser = factory.newSAXParser();

        DefaultHandler handler = new DefaultHandler() {

        boolean bid = false;
        boolean bworkflow = false;
        boolean bstatus = false;
        boolean bjob = false;

        public void startElement(String uri, String localName,
        String qName, Attributes attributes)
        throws SAXException {

        System.out.println("Start Element :" + qName);

        if (qName.equalsIgnoreCase("ID")) {
        bid = true;
        }

        if (qName.equalsIgnoreCase("WORKFLOW")) {
        bworkflow = true;
        }

        if (qName.equalsIgnoreCase("STATUS")) {
        bstatus = true;
        }

        if (qName.equalsIgnoreCase("JOB")) {
        bjob = true;
        }

        }

        public void endElement(String uri, String localName,
        String qName)
        throws SAXException {

        if(qName.equalsIgnoreCase("JOB")){
        jobsVector.add(job);
        }
        if(qName.equalsIgnoreCase("JOBS")){
        resultsTable.setValue(jobsVector);
        }

        System.out.println("End Element :" + qName);

        }

        public void characters(char ch[], int start, int length)
        throws SAXException {

        if (bjob) {
        System.out.println("JOB : " + new String(ch, start, length));
        job = new JobDetails();
        bjob = false;
        }

        if (bid) {
        System.out.println("ID : " + new String(ch, start, length));
        job.setID(new String(ch, start, length));
        bid = false;
        }

        if (bworkflow) {
        System.out.println("WORKFLOW : " + new String(ch, start, length));
        job.setWorkflow(new String(ch, start, length));
        bworkflow = false;
        }

        if (bstatus) {
        System.out.println("STATUS : " + new String(ch, start, length));
        job.setStatus(new String(ch, start, length));
        bstatus = false;
        }


        }
        };

        saxParser.parse("http://rpc103.cs.man.ac.uk:8081/taverna-server-0.2.1/rest/jobs", handler);

        } catch (Exception e) {
        e.printStackTrace();
        }*/




        try {
            DocumentBuilderFactory Factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = Factory.newDocumentBuilder();
            Document doc = builder.parse("http://localhost:9090/taverna-server-0.2.1/rest/jobs");
            //creating an XPathFactory:
            XPathFactory factory = XPathFactory.newInstance();
            //using this factory to create an XPath object:
            XPath xpath = factory.newXPath();
            //XPath object created compiles the XPath expression for workflows:
            //XPathExpression WFExpr = xpath.compile("//dataMap/entry/value/list/value/text()");
            XPathExpression jobIDExpr = xpath.compile("//Jobs/job/id/text()");
            Object jobIDResult = jobIDExpr.evaluate(doc, XPathConstants.NODESET);
            NodeList jobIDNodeList = (NodeList) jobIDResult;

            XPathExpression jobWorkflowExpr = xpath.compile("//workflow/text()");
            Object jobWorkflowResult = jobWorkflowExpr.evaluate(doc, XPathConstants.NODESET);
            NodeList jobWorkflowNodeList = (NodeList) jobWorkflowResult;

            XPathExpression jobStatusExpr = xpath.compile("//status/text()");
            Object jobStatusResult = jobStatusExpr.evaluate(doc, XPathConstants.NODESET);
            NodeList jobStatusNodeList = (NodeList) jobStatusResult;



            results = new String[jobIDNodeList.getLength()];

            jobDetails = new JobDetails[jobIDNodeList.getLength()];
            numberOfJobs = jobIDNodeList.getLength();
            for (int i = 0; i < jobIDNodeList.getLength(); i++) {

                String name = jobWorkflowNodeList.item(i).getNodeValue();

                /*if (name.equals("5")) {
                name = "pipeline";
                } else if (name.equals("2")) {
                name = "Paget's disease";
                } else if (name.equals("4")) {
                name = "get_germ_uniprotid";
                } else {
                name = "ensembl_gene_id_chicken";
                }*/

                JobDetails job = new JobDetails(jobIDNodeList.item(i).getNodeValue(),
                        name, jobStatusNodeList.item(i).getNodeValue());

                jobDetails[i] = job;

            //results[i] = jobIDNodeList.item(i).getNodeValue();
            }

            resultsTable.setValue(jobDetails);


        } catch (Exception e) {
        }

        return null;

    }

    public String showOutputPorts() {

        resultsTabSet.getChildren().clear();

        selectedJob = jobDetails[(resultsTable.getRowIndex())]; //(JobDetails) jobsVector.get(resultsTable.getRowIndex());
        System.out.println();
        System.out.println(selectedJob.workflow);
        if (selectedJob.workflow.equals("pipeline")) {
            outHeader.setValue("Count");
        } else {
            outHeader.setValue("Gene_IDs");
        }

        selectedJobID = selectedJob.ID;
        outs.setValue("Outputs for Job " + selectedJobID);

        outsVis = true;

        try {

            DocumentBuilderFactory Factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = Factory.newDocumentBuilder();

            Document outputsIDDoc = builder.parse("http://localhost:9090/taverna-server-0.2.1/rest/jobs/" + selectedJobID);

            //creating an XPathFactory:
            XPathFactory factory = XPathFactory.newInstance();
            //using this factory to create an XPath object:
            XPath xpath = factory.newXPath();

            XPathExpression outputIDExpr = xpath.compile("//Job/outputs/text()");
            Object outputIDResult = outputIDExpr.evaluate(outputsIDDoc, XPathConstants.NODESET);
            NodeList outputIDNodeList = (NodeList) outputIDResult;

            String outputID = outputIDNodeList.item(0).getNodeValue();
            System.out.println("Output data ID: " + outputID);

            Document outputsDoc = builder.parse("http://localhost:9090/taverna-server-0.2.1/rest/data/" + outputID);

            XPathExpression outputPortsExpr = xpath.compile("//entry/key/text()");
            //XPathExpression WFExpr = xpath.compile("//Jobs/job/id/text()");
            Object outputPortsResult = outputPortsExpr.evaluate(outputsDoc, XPathConstants.NODESET);
            NodeList outputPortsNodeList = (NodeList) outputPortsResult;

            /*XPathExpression anyContainsErrorExpr = xpath.compile("//dataMap/entry/value/containsError/text()");
            //XPathExpression WFExpr = xpath.compile("//Jobs/job/id/text()");
            Object anyContainsErrorResult = anyContainsErrorExpr.evaluate(outputsDoc, XPathConstants.NODESET);
            NodeList anyContainsErrorNodeList = (NodeList) anyContainsErrorResult;

            if (Boolean.parseBoolean(anyContainsErrorNodeList.item(0).getNodeValue()) == false) {
            errorsIcon = "/resources/icons/png/16x16/OK.png";
            } else {
            errorsIcon = "/resources/icons/png/16x16/Error.png";
            }

            XPathExpression containsErrorExpr = xpath.compile("//containsError/text()");
            //XPathExpression WFExpr = xpath.compile("//Jobs/job/id/text()");
            Object containsErrorResult = containsErrorExpr.evaluate(outputsDoc, XPathConstants.NODESET);
            NodeList containsErrorNodeList = (NodeList) containsErrorResult;

            XPathExpression containsErrorExpr1 = xpath.compile("//errorValue/message/text()");
            //XPathExpression WFExpr = xpath.compile("//Jobs/job/id/text()");
            Object containsErrorResult1 = containsErrorExpr1.evaluate(outputsDoc, XPathConstants.NODESET);
            NodeList containsErrorNodeList1 = (NodeList) containsErrorResult1;

             */

            String[] outputPorts = new String[outputPortsNodeList.getLength()];

            for (int i = 0; i < outputPortsNodeList.getLength(); i++) {


                /*if (Boolean.parseBoolean(containsErrorNodeList.item(i).getNodeValue()) == true) {
                errorsMessage = "Contains errors";//"/resources/icons/png/16x16/OK.png");
                dv.setContainsError(true);
                dv.setValue(containsErrorNodeList1.item(0).getNodeValue());//containsErrorNodeList1.item(i).getNodeValue());

                } else {
                dv.setIcon("/resources/icons/png/16x16/Error.png");
                dv.setValue(valueNodeList.item(i).getNodeValue());
                dv.setList(null);
                dv.setContainsError(Boolean.parseBoolean(containsErrorNodeList.item(i).getNodeValue()));

                }*/
                PanelTab panelTab = new PanelTab();
                HtmlPanelGrid htmlPanelGrid = new HtmlPanelGrid();
                HtmlInputText htmlInputText = new HtmlInputText();

                htmlPanelGrid.getChildren().add(htmlInputText);
                panelTab.getChildren().add(htmlPanelGrid);

                resultsTabSet.getChildren().add(panelTab);

                outputPorts[i] = outputPortsNodeList.item(i).getNodeValue();

            }

            outputPortsTable.setValue(outputPorts);

        //sessionBean.jobOutputs.put(selectedJobID, outputs);

        } catch (Exception e) {
            //outputsTable.setValue("Error: " + e);

            System.out.println(e);
        }

        showOutputs();

        return null;
    }

    public String showOutputs() {

        errorsMessage = "Contains no errors";

        outsVis = true;

        int selectedOutputPort = outputPortsTable.getRowIndex();

        if (selectedOutputPort == -1) {
            selectedOutputPort = 0;
        }

        System.out.println(selectedOutputPort + ", " + outputPortsTable.getRowIndex());
        //int jobid = Integer.parseInt(selectedJobID);

        //JobDetails selectedJob = jobDetails[0];//(resultsTable.getRowIndex())]; //(JobDetails) jobsVector.get(resultsTable.getRowIndex());
        System.out.println();
        System.out.println(selectedJob.workflow);
        /*if (selectedJob.workflow.equals("pipeline")) {
        outHeader.setValue("Count");
        } else {
        outHeader.setValue("Gene_IDs");
        }*/

        String selectedJobId = selectedJob.ID;
        outs.setValue("Outputs for Job " + selectedJobID);

        System.out.println("Selected job ID: " + selectedJobID);

        boolean jobInCache = sessionBean.jobOutputs.containsKey(selectedJobID);
        System.out.println("Selected job in hashmap: " + jobInCache);

        if (jobInCache == false) {

            /*try {

            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser saxParser = factory.newSAXParser();

            DefaultHandler handler = new DefaultHandler() {

            boolean bkey = false;
            boolean bvalue = false;
            boolean bcontainsError = false;
            boolean bentry = false;

            public void startElement(String uri, String localName,
            String qName, Attributes attributes)
            throws SAXException {

            System.out.println("Start Element :" + qName);

            if (qName.equalsIgnoreCase("KEY")) {
            bkey = true;
            }

            if (qName.equalsIgnoreCase("VALUE")) {

            dataValue = new DataValue();
            bvalue = true;
            }

            if (qName.equalsIgnoreCase("CONTAINSERROR")) {
            bcontainsError = true;
            }

            if (qName.equalsIgnoreCase("ENTRY")) {
            outputsVector = new Vector();
            bentry = true;
            }

            }

            public void endElement(String uri, String localName,
            String qName)
            throws SAXException {

            if (qName.equalsIgnoreCase("ENTRY")) {
            outputsTable.setValue(outputsVector);
            }
            if (qName.equalsIgnoreCase("VALUE")) {

            outputsVector.add(dataValue);
            resultsTable.setValue(jobsVector);
            }

            System.out.println("End Element :" + qName);

            }

            public void characters(char ch[], int start, int length)
            throws SAXException {

            if (bentry) {
            bentry = false;
            }

            if (bkey) {
            System.out.println("KEY : " + new String(ch, start, length));

            bkey = false;
            }

            if (bvalue) {
            System.out.println("VALUE : " + new String(ch, start, length));
            dataValue.setValue(new String(ch, start, length));
            bvalue = false;
            }

            /*if (bstatus) {
            System.out.println("STATUS : " + new String(ch, start, length));
            job.setStatus(new String(ch, start, length));
            bstatus = false;
            }


            }
            };

            saxParser.parse("http://rpc103.cs.man.ac.uk:8081/taverna-server-0.2.1/rest/data/18"/*+selectedJobId, handler);

            } catch (Exception e) {
            e.printStackTrace();
            }*/

            try {

                DocumentBuilderFactory Factory = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = Factory.newDocumentBuilder();

                Document outputsIDDoc = builder.parse("http://localhost:9090/taverna-server-0.2.1/rest/jobs/" + selectedJobId);

                //creating an XPathFactory:
                XPathFactory factory = XPathFactory.newInstance();
                //using this factory to create an XPath object:
                XPath xpath = factory.newXPath();

                XPathExpression outputIDExpr = xpath.compile("//Job/outputs/text()");
                Object outputIDResult = outputIDExpr.evaluate(outputsIDDoc, XPathConstants.NODESET);
                NodeList outputIDNodeList = (NodeList) outputIDResult;

                String outputID = outputIDNodeList.item(0).getNodeValue();
                System.out.println("Output data ID: " + outputID);

                Document outputsDoc = builder.parse("http://localhost:9090/taverna-server-0.2.1/rest/data/" + outputID);

                XPathExpression valueExpr = xpath.compile("//entry[" + (selectedOutputPort + 1) + "]/value//value/text()");
                //XPathExpression WFExpr = xpath.compile("//Jobs/job/id/text()");
                Object valueResult = valueExpr.evaluate(outputsDoc, XPathConstants.NODESET);
                NodeList valueNodeList = (NodeList) valueResult;

                XPathExpression anyContainsErrorExpr = xpath.compile("//dataMap/entry/value/containsError/text()");
                //XPathExpression WFExpr = xpath.compile("//Jobs/job/id/text()");
                Object anyContainsErrorResult = anyContainsErrorExpr.evaluate(outputsDoc, XPathConstants.NODESET);
                NodeList anyContainsErrorNodeList = (NodeList) anyContainsErrorResult;

                if (Boolean.parseBoolean(anyContainsErrorNodeList.item(0).getNodeValue()) == false) {
                    errorsIcon = "/resources/icons/png/16x16/OK.png";
                } else {
                    errorsIcon = "/resources/icons/png/16x16/Error.png";
                }

                XPathExpression containsErrorExpr = xpath.compile("//containsError/text()");
                //XPathExpression WFExpr = xpath.compile("//Jobs/job/id/text()");
                Object containsErrorResult = containsErrorExpr.evaluate(outputsDoc, XPathConstants.NODESET);
                NodeList containsErrorNodeList = (NodeList) containsErrorResult;

                XPathExpression containsErrorExpr1 = xpath.compile("//errorValue/message/text()");
                //XPathExpression WFExpr = xpath.compile("//Jobs/job/id/text()");
                Object containsErrorResult1 = containsErrorExpr1.evaluate(outputsDoc, XPathConstants.NODESET);
                NodeList containsErrorNodeList1 = (NodeList) containsErrorResult1;


                outputs = new DataValue[valueNodeList.getLength()];

                for (int i = 0; i < valueNodeList.getLength(); i++) {

                    DataValue dv = new DataValue();
                    if (Boolean.parseBoolean(containsErrorNodeList.item(i).getNodeValue()) == true) {
                        errorsMessage = "Contains errors";//"/resources/icons/png/16x16/OK.png");
                        dv.setContainsError(true);
                        dv.setValue(containsErrorNodeList1.item(0).getNodeValue());//containsErrorNodeList1.item(i).getNodeValue());

                    } else {
                        dv.setIcon("/resources/icons/png/16x16/Error.png");
                        dv.setValue(valueNodeList.item(i).getNodeValue());
                        dv.setList(null);
                        dv.setContainsError(Boolean.parseBoolean(containsErrorNodeList.item(i).getNodeValue()));

                    }

                    outputs[i] = dv;

                }


                sessionBean.jobOutputs.put(selectedJobId, outputs);
                outputsTable.setValue(outputs);

                System.out.println("In HashMap: " + sessionBean.jobOutputs);

                System.out.println("Contains errors: " + outputs[0].getContainsError());

            //sessionBean.jobOutputs.put(selectedJobID, outputs);

            } catch (Exception e) {
                //outputsTable.setValue("Error: " + e);
                DataValue dv = new DataValue();
                dv.setValue("No outputs!");
                dv.setIcon("/resources/icons/png/16x16/Error.png");
                errorsIcon = "/resources/icons/png/16x16/Error.png";
                dv.setContainsError(true);
                errorsMessage = "Contains errors";
                //outputsTable.setValue(dv);
                System.out.println(e);
            }
        } else {
            containsErrors = false;
            errorsIcon = "/resources/icons/png/16x16/OK.png";
            DataValue[] cachedDataValue = sessionBean.jobOutputs.get(selectedJobId);

            //test for empty array
            if (cachedDataValue.length < 1) {
                errorsIcon = "/resources/icons/png/16x16/Error.png";
                errorsMessage = "No output";
            }

            outputsTable.setValue(cachedDataValue);
        }


        return null;

    }
    public Vector portResultsVector;

    public Vector getPortResultsVector() {
        return portResultsVector;
    }

    public void setPortResultsVector(Vector v) {
        portResultsVector = v;
    }
    public HtmlDataTable portResultsTable;

    public HtmlDataTable getPortResultsTable() {
        return portResultsTable;
    }

    public void setPortResultsTable(HtmlDataTable hdt) {
        portResultsTable = hdt;
    }

    public String testSAX() {

        //final ValueBinding vb = (ValueBinding) facesContext.getApplication().createValueBinding("#{WorkflowResultsPage.portResultsVector}");
        //final ValueBinding vbCol = facesContext.getApplication().createValueBinding("#{table.description}");

        selectedJob = jobDetails[(resultsTable.getRowIndex())];
        outsVis = true;
        resultsTabSet.getChildren().clear();
        System.out.println("NEW DOC");

        try {

            DocumentBuilderFactory Factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = Factory.newDocumentBuilder();

            Document outputsIDDoc = builder.parse("http://localhost:9090/taverna-server-0.2.1/rest/jobs/" + selectedJob.ID);

            //creating an XPathFactory:
            XPathFactory factory = XPathFactory.newInstance();
            //using this factory to create an XPath object:
            XPath xpath = factory.newXPath();

            XPathExpression outputIDExpr = xpath.compile("//Job/outputs/text()");
            Object outputIDResult = outputIDExpr.evaluate(outputsIDDoc, XPathConstants.NODESET);
            NodeList outputIDNodeList = (NodeList) outputIDResult;

            String outputID = outputIDNodeList.item(0).getNodeValue();
            System.out.println("Output data ID: " + outputID);

            SAXParserFactory SPactory = SAXParserFactory.newInstance();
            SAXParser saxParser = SPactory.newSAXParser();

            DefaultHandler handler = new DefaultHandler() {

                boolean entryFlag = false;
                boolean keyFlag = false;
                boolean valueFlag = false;
                boolean errorFlag = false;
                boolean exceptionFlag = false;
                Vector errorsVector;
                PanelTab panelTab;

                public void startElement(String uri, String localName, String qName,
                        Attributes attributes) {


                    System.out.println("Start Element :" + qName);

                    if (qName.equalsIgnoreCase("ENTRY")) {
                        entryFlag = true;
                        portResultsVector = new Vector();
                        errorsVector = new Vector();

                    }

                    if (qName.equalsIgnoreCase("KEY")) {
                        keyFlag = true;

                        panelTab = new PanelTab();
                        portResultsTable = new HtmlDataTable();
                        //portResultsTable.setValueBinding("value", vb);
                        portResultsTable.setScrollable(true);
                        portResultsTable.setScrollHeight("300px");
                        portResultsTable.setColumnWidths("250px");
                        portResultsTable.setVar("table");
                        portResultsTable.setValueBinding("value", (ValueBinding) facesContext.getApplication().createValueBinding("#{WorkflowResultsPage.portResultsVector}"));

                        ValueBinding vb = facesContext.getApplication().createValueBinding("#{table}");
                        HtmlOutputText output = new HtmlOutputText();
                        output.setId("outputText");
                        output.setValueBinding("value", vb);
                        UIColumn column = new UIColumn();
                        column.setId("col1");
                        column.getChildren().add(output);
                        portResultsTable.getChildren().add(column);
                    //HtmlOutputText ot = new HtmlOutputText();

                    }

                    if (qName.equalsIgnoreCase("VALUE") && attributes.getValue("xsi:type") != null) {
                        valueFlag = true;
                    }

                    if (qName.equalsIgnoreCase("CONTAINSERROR")) {
                        errorFlag = true;
                    }

                    if (qName.equalsIgnoreCase("MESSAGE")) {
                        exceptionFlag = true;
                    }


                }

                public void endElement(String uri, String localName,
                        String qName)
                        throws SAXException {

                    System.out.println("End Element :" + qName);

                    if (qName.equalsIgnoreCase("ENTRY")) {

                        HtmlOutputText errorText = new HtmlOutputText();
                        errorText.setValue(errorsVector.get(0));
                        //System.out.println("ERRORS VALUE!!!!! : "+errorsVector.get(0));
                        if (errorsVector.contains("Errors")) {
                            errorText.setStyle("color:red; font-weight:bold");

                        } else {
                            errorText.setStyle("color:green; font-weight:bold");
                        }
                        //System.out.println(portResultsVector.get(0));
                        //portResultsVector.add(0, errorsVector.get(0));
                        panelTab.getChildren().add(errorText);
                        portResultsTable.setValue(portResultsVector);
                        //portResultsTable.getChildren().add(column);
                        panelTab.getChildren().add(portResultsTable);
                        resultsTabSet.getChildren().add(panelTab);
                    //System.out.println(portResultsVector.get(1));
                    }

                }

                public void characters(char ch[], int start, int length)
                        throws SAXException {

                    if (entryFlag) {
                        System.out.println("Entry: " + new String(ch, start, length));
                        entryFlag = false;
                    }

                    if (keyFlag) {
                        System.out.println("Key: " + new String(ch, start, length));
                        panelTab.setLabel(new String(ch, start, length));
                        keyFlag = false;
                    }

                    if (valueFlag) {
                        System.out.println("Value: " + new String(ch, start, length));
                        String vs = new String(ch, start, length);
                        portResultsVector.add(vs);
                        //column.getChildren().add(value);
                        valueFlag = false;
                    }

                    if (errorFlag) {

                        System.out.println("Error : " + new String(ch, start, length));
                        String error = new String(ch, start, length);
                        if (error.equals("true")) {
                            errorsVector.add("Errors");
                        } else {
                            errorsVector.add("No errors");
                        }
                        errorFlag = false;
                    }

                    if (exceptionFlag) {
                        String vs = new String(ch, start, length);
                        portResultsVector.add(vs);
                        exceptionFlag = false;
                    }

                }
            };

            saxParser.parse("http://localhost:9090/taverna-server-0.2.1/rest/data/" + outputID, handler);

        } catch (Exception e) {
            e.printStackTrace();
        }


        return null;
    }


    //prompts user to confirm job deletion
    public String confirmDelete() {
        JobDetails selectedJob = jobDetails[resultsTable.getRowIndex()];
        selectedJobID = selectedJob.ID;
        popupVis = true;
        return null;
    }

    //cancels the deletion
    public String cancelDelete() {
        popupVis = false;
        return null;
    }

    //method that sends a delete job request to the server and refreshes the jobs
    public String deleteJob() {

        popupVis = false;

        RESTClient tavernaRESTClient = new RESTClient();
        tavernaRESTClient.setBaseURL("http://localhost:9090/taverna-server-0.2.1/rest");

        //JobDetails selectedJob = jobDetails[resultsTable.getRowIndex()];

        //String selectedJobID = selectedJob.ID;
        long selectedJobIDLong = Long.parseLong(selectedJobID.trim());

        tavernaRESTClient.deleteJob(selectedJobIDLong);

        showJobs();

        return null;

    }

    /**
     * <p>Return a reference to the scoped data bean.</p>
     *
     * @return reference to the scoped data bean
     */
    protected ApplicationBean1 getApplicationBean() {
        return (ApplicationBean1) getBean("ApplicationBean");
    }

    /**
     * <p>Return a reference to the scoped data bean.</p>
     *
     * @return reference to the scoped data bean
     */
    protected RequestBean1 getRequestBean() {
        return (RequestBean1) getBean("RequestBean");
    }

    /**
     * <p>Return a reference to the scoped data bean.</p>
     *
     * @return reference to the scoped data bean
     */
    protected SessionBean getSessionBean() {
        return (SessionBean) getBean("SessionBean");
    }
}

